import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms";
import {ProductService} from "../../service/product/product.service";

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {

  formModel: FormGroup;

  categorys: string[];

  constructor(private  service: ProductService) {
    let fb = new FormBuilder();
    this.formModel = fb.group({
      title: ['', Validators.minLength(3)],
      price: [null, this.productPriceValidator],
      category: ['-1']
    });
  }

  ngOnInit() {
    this.categorys = this.service.getAllCategories();
  }

  productPriceValidator(control: FormControl): any {
    if (!control.value) {
      return null;
    }
    let price = parseInt(control.value);
    return price > 0 ? null : {price: {msg: '价格不能为负'}};
  }

  onSearch(){
    console.log(this.formModel.valid);
    if(this.formModel.valid){
      console.log(this.formModel.value);
      this.service.searchEvent.emit(this.formModel.value)
    }
  }
}
